import { calculateDate, getStringDate, error } from '../../lib/js/utils'
import { createActivity } from '../../api/activity'
import { IMAGE_SERVER_URL } from '../../api/config'
import { uploadImage } from '../../api/image'
import { getAllOccupation } from '../../api/occupation'

Page({
  /**
   * 上传图片，可以上传多个
   */
  uploadImages: function(params) {
    const that = this
    wx.chooseMessageFile({
      count: 5,
      type: 'image',
      extension: ['jpg', 'jpeg', 'png', 'bmp', 'wbmp'],
      success(res) {
        // 进行文件上传
        res.tempFiles.forEach(element => {
          uploadImage(element.path).then(
            function(res) {
              // 使用 wx.uploadFile() 后返回的数据是字符串，不是对象
              // 需要手动调用 JSON.parse()
              // 将返回的 url 添加到 data 中
              res.data.forEach(item => {
                if (item.url.indexOf('http') == -1) {
                  item.url = `${IMAGE_SERVER_URL}/${item.url}`
                } else {
                  item.url = `${item.url}`
                }
                that.data.slectedImageUrls.push(item)
                var tempImageUrls = that.data.slectedImageUrls
                that.setData({
                  slectedImageUrls: tempImageUrls
                })
              })
            },
            function(res) {
              error('上传失败')
            }
          )
        })
      }
    })
  },
  /**
   * 提交表单
   * @param {event} e
   */
  doSubmit: function(e) {
    const that = this
    const title = e.detail.value.title
    const activityDescribe = e.detail.value.activityDescribe
    const address = e.detail.value.address

    const startTime = that.data.startDate
    const endTime = that.data.endDate
    const occupations = []
    that.data.occupations.map(item => {
      if (item.isSelected) {
        occupations.push({ occupationId: item.id, num: item.num })
      }
    })
    const registrationFee = e.detail.value.registrationFee
    const imageIds = []
    that.data.slectedImageUrls.forEach(item => {
      imageIds.push(item.id)
    })
    // 发送请求给后端
    createActivity({
      activityDescribe: activityDescribe,
      address: address,
      endTime: endTime,
      imageIds: imageIds,
      occupations: occupations,
      registrationFee: registrationFee,
      startTime: startTime,
      title: title
    }).then(function(res) {
      // 发送成功回调
      console.log(res)
      wx.showToast({
        title: '发布成功！',
      })
    })
  },

  /**
   * 页面的初始数据
   */
  data: {
    startDate: getStringDate(),
    startTime: '00:00:00',
    endDate: getStringDate(),
    endTime: '00:00:00',
    imageIds: [],
    pickerStartDate: getStringDate(),
    pickerEndDate: getStringDate(calculateDate(365 * 10)),

    slectedImageUrls: [],
    // 所有职业
    occupations: [],
    occupationMultiPickerRange: [[], []],
    showOccupationPickerVisible: false
  },
  /**
   * 加载业务参数
   */
  initData: function() {
    const that = this
    // 加载所有职业，并且附加参数
    getAllOccupation().then(function(res) {
      const occupations = res.data.map(item => {
        // 初始化没有被选中
        item.isSelected = false
        // 初始化数量为0
        item.num = 0
        return item
      })

      that.setData({
        occupations: occupations
      })

      // 职业的多选picker数据
      const occupationNames = occupations.map(item => {
        return item.occupationName
      })
      const numRange = []
      for (var i = 1; i <= 20; i++) numRange.push(i)
      that.setData({
        occupationMultiPickerRange: [occupationNames, numRange]
      })
    })
  },
  /**
   * 删除选中的图片
   * @param {*} e
   */
  deleteImage: function(e) {
    const that = this
    const index = e.currentTarget.dataset.index
    const slectedImageUrls = that.data.slectedImageUrls
    slectedImageUrls.splice(index, 1)
    that.setData({
      slectedImageUrls: slectedImageUrls
    })
  },
  /**
   * 选择职业以及人数
   * @param {*} e
   */
  changeMultiOccupation: function(e) {
    const that = this
    const occupationNameIndex = e.detail.value[0]
    const occupationNumIndex = e.detail.value[1]
    const occupations = that.data.occupations
    occupations[occupationNameIndex].isSelected = true
    occupations[occupationNameIndex].num = that.data.occupationMultiPickerRange[1][occupationNumIndex]

    occupations
    that.setData({
      occupations
    })
  },
  /**
   * 取消选择职业以及人数
   * @param {*} e
   */
  cancleOccupation: function(e) {
    const that = this
    const index = e.currentTarget.dataset.index
    const occupations = that.data.occupations
    occupations[index].isSelected = false
    occupations[index].num = 0
    that.setData({
      occupations: occupations
    })
  },
  /**
   * 改变开始时间
   * @param {*} e
   */
  changeStartDate: function(e) {
    var startDate = e.detail.value
    var endDate = getStringDate(calculateDate(10, new Date(Date.parse(startDate))))
    this.setData({
      startDate: startDate,
      endDate: endDate
    })
  },
  /**
   * 改变结束时间
   * @param {*} e
   */
  changeEndDate: function(e) {
    var endDate = e.detail.value
    this.setData({
      endDate: endDate
    })
  },
  /**
   * 显示职业人数picker选择器
   */
  showOccupationPickerVisible: function(e) {
    var flag = e.currentTarget.dataset.flag
    this.setData({
      showOccupationPickerVisible: flag
    })
  },
  /**
   * 确定选择职业以及人数
   * @param {*} options
   */
  occupationConfirm: function(e) {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.initData()
  }
})
